<template>
  <div class="config-query-managner">
    <div class="query-from">
      <el-form>
        <el-row :gutter="20">
          <el-col :span="4">
            <el-form-item label="产品" label-width="80px">
              <el-select-v2 v-model="queryParam.product_id" filterable :options="selectProductList"
                placeholder="请选择查询的产品" style="width: 100%" clearable :props="{
                  value: 'product_id',
                  label: 'product_name'
                }" >

                <template #default="{ item }">
                  <el-tooltip
                      effect="dark"
                      :content="item.product_name"
                      placement="right"
                      :open-delay="500"
                      :hide-after="0"
                  >
                    <span class="truncate">{{ item.product_name }}</span>
                  </el-tooltip>
                </template>

              </el-select-v2>
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <el-form-item label="渠道" label-width="80px">
              <el-select-v2 v-model="queryParam.channel_id" filterable :options="selectChannelList"
                placeholder="请选择查询的渠道" style="width: 100%" clearable :props="{
                  value: 'channel_id',
                  label: 'channel_name'
                }" >
                <template #default="{ item }">
                  <el-tooltip
                      effect="dark"
                      :content="item.channel_name"
                      placement="right"
                      :open-delay="500"
                      :hide-after="0"
                  >
                    <span class="truncate">{{ item.channel_name }}</span>
                  </el-tooltip>
                </template>

              </el-select-v2>
            </el-form-item>

          </el-col>

          <el-col :span="4">
            <el-form-item label="客户" label-width="80px">
              <el-select-v2 v-model="queryParam.customer_id" filterable :options="selectCustomerList"
                placeholder="请选择查询的客户" style="width: 100%" clearable :props="{
                  value: 'customer_id',
                  label: 'customer_shortname'
                }" >
                <template #default="{ item }">
                  <el-tooltip
                      effect="dark"
                      :content="item.customer_shortname"
                      placement="right"
                      :open-delay="500"
                      :hide-after="0"
                  >
                    <span class="truncate">{{ item.customer_shortname }}</span>
                  </el-tooltip>
                </template>

              </el-select-v2>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="创建时间" label-width="80px">
              <div style="display: flex; gap: 8px; align-items: center">
                <el-date-picker v-model="queryParam.start_time" type="datetime" disabled style="width: 180px"
                  format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
                <span>到</span>
                <el-date-picker v-model="queryParam.end_time" type="datetime" placeholder="请选择结束时间" style="width: 180px"
                  format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" />
              </div>
            </el-form-item>
          </el-col>



        </el-row>

        <el-row :gutter="20">
          <el-col :span="4">
            <el-form-item label="打印类型" label-width="80px">
              <el-select-v2 v-model="queryParam.print_type" filterable :options="printTypeList" placeholder="请选择查询的打印类型"
                style="width: 100%" clearable :props="{
                  value: 'code',
                  label: 'desc'
                }" />
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <el-form-item label="状态" label-width="80px">
              <el-select-v2 v-model="queryParam.status" filterable :options="printConfigStatuList"
                placeholder="请选择查询的状态" style="width: 100%" clearable :props="{
                  value: 'code',
                  label: 'desc'
                }" />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="COS服务商" label-width="80px">
              <el-select-v2 v-model="queryParam.cos_server_type" filterable :options="cosServerList"
                placeholder="请选择查询的COS" style="width: 100%" clearable :props="{
                  value: 'code',
                  label: 'desc'
                }" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" justify="end">
          <el-col :span="4" :offset="16" style="text-align: right;">
            <el-button type="primary" @click="onSearch" :loading="loading" :disabled="loading">查询</el-button>
            <el-button @click="onReset" style="margin-left: 10px;">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="base-tabel">
      <div class="tabel-action">
        <el-button type="primary" @click="handleAdd">添加</el-button>
        <el-button type="primary" @click="batchHandleRowOpenColseClick('ON')">开启</el-button>
        <el-button type="primary" @click="batchHandleRowOpenColseClick('OF')">关闭</el-button>
        <el-button type="primary" @click="openRePushDialog()">按时间重推面单</el-button>
        <el-button type="primary" @click="openLogsDialog()">日志</el-button>
      </div>

    

  
        <span v-if="selectedRowsCount > 0" style="color: #409EFF;">
          ✅ 已选择 {{ selectedRowsCount }} 条记录
        </span>


        <el-table ref="tableRef" :data="tableData" style="width: 100%" max-height="560px" :stripe="true" :border="true"
          highlight-current-row :row-key="row => row.id" @selection-change="handleSelectionChange" v-loading="loading"
          :element-loading-svg="svg" class="custom-loading-svg">
          <el-table-column type="selection" width="40" align="center" reserve-selection />
          <el-table-column fixed prop="status_name" label="规则状态" width="80" align="center" />
          <el-table-column fixed prop="name" label="规则名称" width="150" align="center" />
          <el-table-column prop="product_name" label="适用产品" show-overflow-tooltip min-width="150" align="center" />
          <el-table-column prop="channel_name" label="适用渠道" show-overflow-tooltip min-width="150" align="center" />
          <el-table-column prop="customer_shortname" label="适用客户" show-overflow-tooltip min-width="150"
            align="center" />
          <el-table-column prop="print_type_name" label="标签类型" width="150" align="center" />
          <el-table-column prop="create_date" label="创建时间" width="150" align="center" />
          <el-table-column prop="label_push_start_date" label="推送起始时间" width="150" align="center" />
          <el-table-column prop="cos_server_type_name" label="COS云服务商" width="150" align="center" />
          <el-table-column prop="match_orders" label="符合订单" width="100" align="center">
            <template #default="{ row }">
              <el-link type="primary" @click="router.push({
                path: '/order/orderQuery', query: {
                  label_config_id: row.id,
                  product_id: row.product_id,
                  label_push_start_date: row.label_push_start_date,
                  print_type: row.print_type,
                  channel_id: row.channel_id,
                  customer_id: row.customer_id
                }
              })">
                  <span style="color: black;">{{ row.match_orders }} </span>
              </el-link>
            </template>
          </el-table-column>

          <el-table-column prop="push_orders" label="已推送订单" width="100" align="center">
            <template #default="{ row }">
              <el-link type="primary" @click="router.push({
                path: '/order/orderQuery', query: {
                  label_config_id: row.id,
                  product_id: row.product_id,
                  label_push_start_date: row.label_push_start_date,
                  push_cos_sign: 'Y',
                  print_type: row.print_type,
                  channel_id: row.channel_id,
                  customer_id: row.customer_id
                }
              })">
              <span style="color: green;">{{ row.push_orders }}</span>
                
              </el-link>
            </template>
          </el-table-column>

          <el-table-column prop="not_push_orders" label="未推送订单" width="100" align="center">
            <template #default="{ row }">
              <el-link type="primary" @click="router.push({
                path: '/order/orderQuery', query: {
                  label_config_id: row.id,
                  product_id: row.product_id,
                  label_push_start_date: row.label_push_start_date,
                  push_cos_sign: 'N',
                  print_type: row.print_type,
                         channel_id: row.channel_id,
                  customer_id: row.customer_id,
                }
              })">
                     <span style="color: red;">{{ row.not_push_orders }}</span>
                
              </el-link>
            </template>
          </el-table-column>
          <el-table-column fixed="right" prop="" label="操作" show-overflow-tooltip min-width="150" align="center">
            <template #default="{ row }">
              <div>
                <el-button link type="primary" size="small" @click="handleRowEditClick(row)">编辑</el-button>
                <el-button link type="primary" size="small" @click="handleRowOpenClick(row)">开启</el-button>
                <el-button link type="primary" size="small" @click="handleRowColseClick(row)">关闭</el-button>
              </div>


            </template>
          </el-table-column>
        </el-table>




        <div class="demo-pagination-block">
          <el-pagination v-model:current-page="queryParam.pageNumber" v-model:page-size="queryParam.pageSize"
            :page-sizes="[20, 50, 100]" :background="true" layout="total, sizes, prev, pager, next, jumper"
            :total="currentTotalData" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
   
    </div>



    <LabelConfigForm v-model="showLabelConfigFrom" :record-key="currentRowKey" :on-submit="handleSubmitToAPI"
      :exc-success="refreshTable" :get-detail="getDetail" />

    <LabelRePushForm ref="rePushRef" @confirm="onRePushConfirm" />

    <BusinessLogDialog ref="logDialog" v-model="showLogDialog"/>

  </div>
</template>

<script setup>



//一些导入
import { queryLabelConfigCondition, rePushLabel, saveLabelConfig, selectLabelConfigById, updateLabelStatus } from '@/api'
import { onMounted, ref, watch, computed } from 'vue'
import dayjs from 'dayjs'
import { useDictStore } from '@/store/dictStore'
import { ElMessage } from 'element-plus'
import LabelConfigForm from './labelconfig/LabelConfigForm.vue'
import { useRouter } from 'vue-router'
import LabelRePushForm from './labelconfig/LabelRePushForm.vue'
import BusinessLogDialog from "@/views/log/BusinessLogDialog.vue";

const router = useRouter()
//加载字典
const dictStore = useDictStore()

const rePushRef = ref()

const logDialog = ref()

const showLogDialog = ref(false)

//============================================================================================================================
//定义一些参数
// 全部勾选的数据
let selectedRows = ref(new Map())

//定义产品下拉框
let selectProductList = ref([])
//渠道下拉框
let selectChannelList = ref([])
//客户下拉框
let selectCustomerList = ref([])
let currentRowKey = ref(null)

let printTypeList = ref([])
let printConfigStatuList = ref([])
let cosServerList = ref([])
let showLabelConfigFrom = ref(false)

//查询总数
let currentTotalData = ref(0)
//表格的引用
let tableRef = ref(null)
//定义查询Dto
let queryParam = ref({
  pageNumber: 1,
  pageSize: 20,
  start_time: '',
  end_time: '',
  name: '',
  product_id: '',
  channel_id: '',
  customer_id: '',
  status: '',
  print_type: '',
  cos_server_type: ''
})

//定义返回表格的数据
let tableData = ref([])

let loading = ref(false)
const svg = `
        <path class="path" d="
          M 30 15
          L 28 17
          M 25.61 25.61
          A 15 15, 0, 0, 1, 15 30
          A 15 15, 0, 1, 1, 27.99 7.5
          L 15 15
        " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>
      `

//==============================================================================================================================================

//定义一些方法

//根据条件查询
const queryData = async () => {
  try {
    loading.value = true
    await queryLabelConfigCondition(queryParam.value).then(resp => {
      tableData.value = resp.list;
      currentTotalData.value = resp.total;
    })
  } finally {
    loading.value = false
  }
}

//分页查询
const handleSizeChange = (num) => {
  queryParam.value.pageSize = num;
  queryParam.value.pageNumber = 1; // 通常重置页码为1
  queryData()
};

const handleCurrentChange = (num) => {
  queryParam.value.pageNumber = num;
  queryData()
};

const initDateRange = () => {
  const now = dayjs()
  queryParam.value.start_time = '2025-01-01 00:00:00'
  queryParam.value.end_time = now.format('YYYY-MM-DD') + ' 23:59:59'
}

//重置
const onReset = () => {
  Object.keys(queryParam.value).forEach(key => {
    if (Array.isArray(queryParam.value[key])) {
      queryParam.value[key] = []
    } else if (typeof queryParam.value[key] === 'object') {
      queryParam.value[key] = null
    } else {
      queryParam.value[key] = ''
    }
  })

  initDateRange()
  clearSelection()
}

//查询方法
const onSearch = () => {
  const nowEnd = dayjs().endOf('day')
  const endDate = dayjs(queryParam.value.end_time)

  if (endDate.isAfter(nowEnd)) {
    ElMessage.warning('结束时间不能晚于当前时间')
    return
  }

  //重新指定页数
  queryParam.value.pageNumber = 1;


  try {
    //查询
    queryData()

    clearSelection()
  } catch (err) {
    ElMessage.warning('查询异常', err)
  } finally {

  }

}

const handleSelectionChange = (selection) => {
  // 更新 map：把当前页选中的行加进来

  selection.forEach(row => {
    selectedRows.value.set(row.id, row)
  })

  tableData.value.forEach(row => {
    if (selectedRows.value.has(row.id)) {
      if (!selection.some(item => item.id === row.id)) {
        selectedRows.value.delete(row.id)
      }
    }
  })

}


const clearSelection = () => {
  selectedRows.value.clear()
  tableRef.value?.clearSelection()
}


async function initPageData() {
  initDateRange()
  const dicts = await Promise.all([
    dictStore.loadDict('product'),
    dictStore.loadDict('channel'),
    dictStore.loadDict('customer'),
    dictStore.loadDict('getAllPrintType'),
    dictStore.loadDict('getAllPrintConfigStatus'),
    dictStore.loadDict('getAllCosServer'),
  ])

  selectProductList.value = dicts[0]
  selectChannelList.value = dicts[1]
  selectCustomerList.value = dicts[2]
  printTypeList.value = dicts[3]
  printConfigStatuList.value = dicts[4]
  cosServerList.value = dicts[5]
  // requestIdleCallback(async () => {
  //     selectProductList.value = await dictStore.loadDict('product')
  // })

  // requestIdleCallback(async () => {
  //     selectChannelList.value = await dictStore.loadDict('channel')
  // })

  // requestIdleCallback(async () => {
  //     selectCustomerList.value = await dictStore.loadDict('customer')
  // })

  // requestIdleCallback(async () => {
  //     printTypeList.value = await dictStore.loadDict('getAllPrintType')
  // })

  // requestIdleCallback(async () => {
  //     printConfigStatuList.value = await dictStore.loadDict('getAllPrintConfigStatus')
  // })

  // requestIdleCallback(async () => {
  //     cosServerList.value = await dictStore.loadDict('getAllCosServer')
  // })

}



const handleAdd = () => {
  currentRowKey.value = null
  showLabelConfigFrom.value = true
}

const handleRowEditClick = (row) => {
  currentRowKey.value = row.id
  showLabelConfigFrom.value = true
}

const handleRowOpenClick = (row) => {
  //请求
  updateLabelStatus(row.id, "ON").then(data => {
    row.status = 'ON'
    row.status_name = '生效'
    const target = tableData.value.find(item => item.id === row.id);
    if (target) {
      target.status = "ON";
      target.status_name = "生效";
    }
    ElMessage.success("成功")
  })
}

const handleRowColseClick = (row) => {
  //请求
  updateLabelStatus(row.id, "OF").then(data => {
    row.status = 'OF'
    row.status_name = '关闭'
    const target = tableData.value.find(item => item.id === row.id);
    if (target) {
      target.status = "OF";
      target.status_name = "关闭";
    }
    ElMessage.success("成功")
  })
}

const batchHandleRowOpenColseClick = (status) => {

  if (selectedRows.value.size === 0) {
    ElMessage.warning('请选择要操作的行')
    return
  }

  // 从 Map 里取所有 id
  const ids = Array.from(selectedRows.value.keys())

  updateLabelStatus(ids, status)
    .then(() => {

      const name = (status === 'ON' ? '生效' : '关闭')

      ElMessage.success(`批量${status === 'ON' ? '开启' : '关闭'}成功`)

      // 更新 Map 里所有行的状态
      selectedRows.value.forEach(row => {
        row.status = status
        row.status_name = name

      })
    })


}

const handleSubmitToAPI = async (data) => {
  // 发请求保存
  return saveLabelConfig(data)
}

const refreshTable = () => {
  tableData.value = [] // 重新加载列表数据

  try {


    clearSelection()

    //查询
    queryData()


  } catch (err) {
    ElMessage.warning('查询异常', err)
  } finally {

  }
}

//根据ID查询信息
const getDetail = (id) => {
  return selectLabelConfigById(id)
}




const onRePushConfirm = (payload) => {


  const ids = Array.from(selectedRows.value.keys())
  
  let submitData = {
    configIds: ids,
    push_start_time: payload.start_time
  }
  rePushLabel(submitData)
  .then(data => {
    if(data.code === 200){
      ElMessage.success('添加成功，后台执行中，请勿重复添加')
    }
    
  })
}

const openRePushDialog = ()=>{

  if (selectedRows.value.size === 0) {
    ElMessage.warning('请选择要操作的行')
    return
  }

  //开启弹窗
  rePushRef.value.open()
}

const openLogsDialog = ()=>{
  if (selectedRows.value.size === 0) {
    ElMessage.warning('请选择要操作的行')
    return
  }
  if (selectedRows.value.size > 1) {
    ElMessage.warning('请勿操作多行')
    return
  }
  let keyset = selectedRows.value.keys()
  // 调用子组件方法
  logDialog.value.open('LABELCONFIG', Array.from(selectedRows.value.keys())[0])
}

//计算属性
let selectedRowsCount = computed(() => selectedRows.value.size)


onMounted(async () => {
  initPageData()
})

</script>

<style scoped lang="scss">

.query-from {
  background-color: #ffffff;
  padding: 20px 20px 0;
  border-radius: 5px;
  padding-bottom: 10px;
  /* 最底部间距 */
}

.base-tabel {
  border-radius: 5px;
  // background: #ffffff;
  margin-top: 20px;
  margin-bottom: 20px;
  .tabel-action {
    border-radius: 5px 5px 0px 0px;
    background: #ffffff;
    padding: 20px;
    border-bottom: 1px solid #ece8e8
  }

  .pagination {
    // margin-top: 10px;
    text-align: center;
    // padding: 20px;
  }
}

.demo-pagination-block {
      border-radius: 0px 0px 5px 5px;
      background: #ffffff;
  margin-top: 1px;
  display: flex;
  justify-content: center;
  height: 40px;
  // padding: 20px 0;
}

.custom-readonly-checkbox {
  pointer-events: none;
  /* 禁止点击 */
}

.truncate {
  display: inline-block;
  max-width: 100%;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
</style>